package be.scond.cartpool;

import java.io.IOException;
import javax.servlet.http.*;
import be.scond.cartpool.API.GroupApi;
import be.scond.cartpool.API.ShoppingListApi;
import be.scond.cartpool.exceptions.ClosedShoppingListFoundException;
import be.scond.cartpool.exceptions.GroupDoesNotExistException;
import be.scond.cartpool.exceptions.NoShoppingListFoundException;
import be.scond.cartpool.exceptions.UserNotFoundException;

public class CloseShoppingListServlet extends HttpServlet {
	
	static final long serialVersionUID = 1;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/xml");		

		String groupName = req.getParameter("groupName");	
		String email = req.getParameter("email");	
		String respons = "<data>";

		String keyString = req.getParameter("key");			
		try {
			ShoppingListApi.closeShoppingList(keyString, email, groupName);	
			
			try {
				String groupInfoXml = GroupApi.getGroupInfo(groupName);	
				respons += "<succes>The list was closed</succes>";
				respons += groupInfoXml;
			} catch (GroupDoesNotExistException e) {
				respons += "<error>group was not found</error>";
			}
			
		} catch (NoShoppingListFoundException e) {
			respons += "<error>No shoppingList with that key found</error>";
		} catch (UserNotFoundException e) {
			respons += "<error>User not found</error>";
		} catch (ClosedShoppingListFoundException e) {
			respons += "<error>shoppingList is already closed</error>";				
		}
			
		respons += "</data>";

		resp.getWriter().print(respons);
	}
}